<template>
  <div class="developer-info">
    <div class="operation-bar">
      <el-button type="primary" @click="toggleUpdate" :loading="updating">
        {{ updateEnabled ? '禁用' : '启用' }}更新开发信息
      </el-button>
    </div>
    <h1>开发信息</h1>
    
    <div class="search-bar">
      <el-input 
        v-model="searchOwner" 
        placeholder="组织名称" 
        clearable 
        @input="searchDeveloperInfos"
      />
      <el-input 
        v-model="searchName" 
        placeholder="库名称" 
        clearable 
        @input="searchDeveloperInfos"
      />
      <el-button type="primary" @click="searchDeveloperInfos">
        <el-icon><Search /></el-icon>
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="showAddDialog">添加开发信息</el-button>
      <el-button type="danger" :disabled="!selectedDevelopers.length" @click="batchDelete">
        批量删除
      </el-button>
    </div>
    
    <el-table 
          :data="paginatedData" 
          style="width: 100%" 
          v-loading="loading"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
      <el-table-column prop="displayId" label="序号" width="80" />
      <el-table-column prop="owner" label="组织名称" width="120" />
      <el-table-column prop="name" label="库名称" width="120" />
      <el-table-column prop="developer" label="开发者" width="120" />
      <el-table-column prop="pullRequest" label="提交的PR" width="600" />
      <el-table-column prop="title" label="PR标题" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDeveloperInfo(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="developerInfos.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑开发信息对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑开发信息' : '添加开发信息'">
      <el-form :model="form" label-width="120px">
        <el-form-item 
          label="组织名称" 
          prop="owner"
          :rules="[
            { required: true, message: '请选择组织名称', trigger: 'change' }
          ]">
          <el-select v-model="form.owner" placeholder="请选择组织名称">
            <el-option label="openharmony-sig" value="openharmony-sig" />
            <el-option label="openharmony-tpc" value="openharmony-tpc" />
            <el-option label="openharmony_tpc_samples" value="openharmony_tpc_samples" />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="库名称" 
          prop="name"
          :rules="[
            { required: true, message: '请输入库名称', trigger: 'blur' }
          ]">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="开发者">
          <el-input v-model="form.developer" />
        </el-form-item>
        <el-form-item label="提交的PR">
          <el-input v-model="form.pullRequest" type="number" />
        </el-form-item>
        <el-form-item label="PR标题">
          <el-input v-model="form.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDeveloperInfo">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { developerInfoApi } from '../api'

export default {
  name: 'DeveloperInfo',
  components: {
    Search
  },
  setup() {
    // 添加 updating 变量
    const updateEnabled = ref(false)
    // 添加多选相关的变量
    const selectedDevelopers = ref([])
    const updating = ref(false)
    const developerInfos = ref([])
    const loading = ref(false)
    const searchOwner = ref('')
    const searchName = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const form = ref({
      id: null,
      owner: '',
      name: '',
      developer: '',
      pullRequest: null,
      title: ''
    })

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    // 获取更新状态
    const getUpdateStatus = async () => {
      try {
        const response = await developerInfoApi.getUpdateStatus()
        updateEnabled.value = response.data
      } catch (error) {
        console.error('获取更新状态失败:', error)
      }
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 添加多选相关的方法
    const handleSelectionChange = (val) => {
      selectedDevelopers.value = val
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedDevelopers.value.length} 条开发信息吗？`, 
          '警告', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 修改：使用 batchDelete API 而不是多个单独的删除请求
        const ids = selectedDevelopers.value.map(developer => developer.id)
        await developerInfoApi.batchDelete(ids)
        
        ElMessage.success('批量删除成功')
        loadDeveloperInfos()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    // 修改更新仓库方法
    const updateAllRepos = async () => {
      updating.value = true
      try {
        const response = await developerInfoApi.toggleUpdate()
        updateEnabled.value = response.data
        ElMessage.success(`${updateEnabled.value ? '启用' : '禁用'}更新功能成功`)
      } catch (error) {
        console.error('切换更新状态失败:', error)
        ElMessage.error('切换更新状态失败')
      } finally {
        updating.value = false
      }
    }

    const toggleUpdate = async () => {
      updating.value = true
      try {
        const response = await developerInfoApi.toggleUpdate()
        updateEnabled.value = response.data
        ElMessage.success(`${updateEnabled.value ? '启用' : '禁用'}更新功能成功`)
      } catch (error) {
        console.error('切换更新状态失败:', error)
        ElMessage.error('切换更新状态失败')
      } finally {
        updating.value = false
      }
    }


    const loadDeveloperInfos = async () => {
      loading.value = true
      try {
        const response = await developerInfoApi.getAll()
        developerInfos.value = response.data
      } catch (error) {
        console.error('加载开发信息失败:', error)
        ElMessage.error('加载开发信息失败')
      } finally {
        loading.value = false
      }
    }

    const searchDeveloperInfos = async () => {
      loading.value = true
      try {
        let response
        if (searchOwner.value && !searchName.value) {
          // 只按组织名称搜索
          response = await developerInfoApi.getByOwner(searchOwner.value)
        } else if (!searchOwner.value && searchName.value) {
          // 只按库名称搜索
          response = await developerInfoApi.getByName(searchName.value)
        } else if (searchOwner.value && searchName.value) {
          // 组合搜索
          response = await developerInfoApi.getByOwnerAndName(searchOwner.value, searchName.value)
        } else {
          // 都为空时获取所有数据
          response = await developerInfoApi.getAll()
        }
        
        if (response.data) {
          developerInfos.value = response.data
          // 检查当前页码是否有效
          const maxPage = Math.ceil(developerInfos.value.length / pageSize.value)
          if (currentPage.value > maxPage) {
            currentPage.value = maxPage || 1
          }
        }
      } catch (error) {
        console.error('搜索开发信息失败:', error)
        ElMessage.error('搜索开发信息失败')
      } finally {
        loading.value = false
      }
    }

    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return developerInfos.value.slice(start, end)
    })

    
    const showAddDialog = () => {
      isEdit.value = false
      form.value = {
        id: null,
        owner: '',
        name: '',
        developer: '',
        pullRequest: null,
        title: ''
      }
      dialogVisible.value = true
    }

    const showEditDialog = (developerInfo) => {
      isEdit.value = true
      form.value = { ...developerInfo }
      dialogVisible.value = true
    }

    const saveDeveloperInfo = async () => {
      try {
        if (isEdit.value) {
          await developerInfoApi.update(form.value)  // 移除 id 参数，直接传整个表单对象
          ElMessage.success('开发信息更新成功')
        } else {
          await developerInfoApi.create(form.value)
          ElMessage.success('开发信息添加成功')
        }
        dialogVisible.value = false
        loadDeveloperInfos()
      } catch (error) {
        console.error('保存开发信息失败:', error)
        ElMessage.error('保存开发信息失败')
      }
    }

    const deleteDeveloperInfo = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条开发信息吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await developerInfoApi.delete(id)
        ElMessage.success('开发信息删除成功')
        loadDeveloperInfos()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除开发信息失败:', error)
          ElMessage.error('删除开发信息失败')
        }
      }
    }

    onMounted(() => {
      loadDeveloperInfos()
      getUpdateStatus()  // 页面加载时获取更新状态
    })

    const resetSearch = () => {
      searchOwner.value = ''
      searchName.value = ''
      loadDeveloperInfos()
    }

    // 在 return 中添加
    return {
      developerInfos,
      loading,
      searchOwner,
      searchName,
      dialogVisible,
      isEdit,
      form,
      currentPage,
      pageSize,
      paginatedData,
      updating,
      updateEnabled,
      selectedDevelopers,
      handleSelectionChange,
      batchDelete,
      toggleUpdate,
      loadDeveloperInfos,
      searchDeveloperInfos,
      resetSearch,
      showAddDialog,
      showEditDialog,
      saveDeveloperInfo,
      deleteDeveloperInfo,
      handleSizeChange,
      handleCurrentChange,
      updateAllRepos
    }
  }
}
</script>

<style scoped>
.developer-info {
  padding: 20px;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  max-width: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  margin-bottom: 60px; /* 添加底部边距，避免被 footer 遮挡 */
}

/* 添加表格容器样式 */
.developer-info {
  padding: 20px;
  min-height: calc(100vh - 200px); /* 确保内容区域有足够的高度 */
}
</style>